<template>
  <div class="waitRepairList-container">
    <div class="app-container">
      <el-card class="box-card">

        <div
          slot="header"
          class="clearfix"
        >
          <span>{{state === 1 ? '待处理报修单' : state === 2 ? '进行中报修单' : state === 3 ? '已完成报修单' : '所有报修单'}}</span>
          <div class="form">
            <el-form
              :inline="true"
              :model="queryForm"
              ref='queryForm'
              :rules='queryRules'
              class="query-form"
            >
              <el-form-item prop='id'>
                <el-input
                  clearable
                  v-model.trim="queryForm.id"
                  placeholder="请输入报修单id"
                  @keyup.enter.native="getQueryFn()"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="getQueryFn()"
                >查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 筛选 -->
        <div class="screen">
          <el-form
            :rules="screenRules"
            inline
            :model="query"
            ref="screenForm"
            v-if="isStudent"
          >
            <el-form-item
              label="报修类型"
              prop="type_id"
            >
              <el-cascader
                placeholder="请选择报修类型"
                v-model="query.type_id"
                :options="repairTypeList"
                filterable
                clearable
                style="width: 180px"
                :props="{ label: 'name', value: 'id', emitPath: false }"
              ></el-cascader>
            </el-form-item>
            <el-form-item
              label="报修单状态"
              prop="state"
              v-if="this.state !== 3"
            >
              <el-select
                clearable
                v-model="query.state"
                placeholder="请选择报修单状态"
                style="width: 180px"
                v-if="this.state === 4"
              >
                <template v-for="(item, index) in repairState">
                  <el-option
                    :key="index"
                    :label="item"
                    :value="index"
                  >
                  </el-option>
                </template>
              </el-select>

              <el-select
                clearable
                v-model="query.state"
                placeholder="请选择报修单状态"
                style="width: 180px"
                v-if="this.state === 1"
              >
                <template v-for="(item, index) in repairState">
                  <el-option
                    v-if="index === '3' || index ==='6'"
                    :key="index"
                    :label="item"
                    :value="index"
                  >
                  </el-option>
                </template>
              </el-select>

              <el-select
                clearable
                v-model="query.state"
                placeholder="请选择报修单状态"
                style="width: 180px"
                v-if="this.state === 2"
              >
                <template v-for="(item, index) in repairState">
                  <el-option
                    v-if="index === '1' || index ==='4'|| index ==='5'|| index ==='7'"
                    :key="index"
                    :label="item"
                    :value="index"
                  >
                  </el-option>
                </template>
              </el-select>

            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="screenSubmitFn()"
              >提交</el-button>
              <el-button @click="screenResetFn()">重置</el-button>
            </el-form-item>
          </el-form>

          <el-form
            :rules="screenRules"
            inline
            :model="query"
            ref="screenForm"
            v-else-if="this.state === 4 || this.state === 2"
          >
            <el-form-item
              label="报修单状态"
              prop="state"
              v-if="this.state === 4"
            >
              <el-select
                clearable
                v-model="query.state"
                placeholder="请选择报修单状态"
                style="width: 180px"
              >
                <template v-for="(item, index) in repairState">
                  <el-option
                    v-if="+index > 3"
                    :key="index"
                    :label="item"
                    :value="index"
                  >
                  </el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item
              label="报修单状态"
              prop="state"
              v-if="this.state === 2"
            >
              <el-select
                clearable
                v-model="query.state"
                placeholder="请选择报修单状态"
                style="width: 180px"
              >
                <template v-for="(item, index) in repairState">
                  <el-option
                    v-if="+index === 5 || index ==='7'"
                    :key="index"
                    :label="item"
                    :value="index"
                  >
                  </el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="screenSubmitFn()"
              >提交</el-button>
              <el-button @click="screenResetFn()">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 列表 -->
        <div
          class="list"
          v-if='repairList[0]'
        >
          <el-row
            class="item"
            v-for="(item) in repairList"
            :key="item.id"
          >

            <el-col :span="21">
              <el-descriptions
                :column="2"
                :colon='false'
                @click.native="$router.push({
              path: `/repair/info/${item.id}`,
              })"
              >
                <el-descriptions-item label="联系电话">：{{item.phone}}</el-descriptions-item>
                <el-descriptions-item label='报修状态'>：<el-tag :type="tagState[item.state]">{{repairState[item.state]}}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="报修类型">：{{item.type_name}}</el-descriptions-item>
                <el-descriptions-item label="提交时间">：{{new Date(item.ctime).toLocaleString()}}</el-descriptions-item>
                <el-descriptions-item label="报修区域">：{{areaOptions[item.a_id]?.label}}</el-descriptions-item>
                <el-descriptions-item label="报修地点">：{{item.place}}</el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col
              :span="3"
              class="handle"
            >
              <el-button
                v-if="isStudent && item.state < 4 && item.state !== 2"
                :type="item.state === 2? 'danger' : 'primary'"
                size="small"
                @click="$router.push(
                    {
                      path: `/repair/update/${item.id}`,
                    }
                  )"
              >修改报修单</el-button>

              <el-popover
                placement="right"
                width="400"
                trigger="click"
              >
                <el-form
                  :inline="true"
                  :model="back"
                  ref="backForm"
                  :rules="backRules"
                  class="demo-form-inline"
                >
                  <el-form-item prop='cause'>
                    <el-input
                      clearable
                      v-model.trim="back.cause"
                      placeholder="请输入驳回原因"
                      @keyup.enter.native="affirmRepairFn(item.id, false)"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      @click="affirmRepairFn(item.id, false)"
                    >确定</el-button>
                  </el-form-item>
                </el-form>
                <el-button
                  size="small"
                  type="danger"
                  slot="reference"
                  v-if="isStudent && item.state === 6"
                >驳回维修完成状态</el-button>
              </el-popover>
              <el-popconfirm
                title="确定维修已完成吗？"
                @confirm="affirmRepairFn(item.id, true)"
              >
                <el-button
                  size="small"
                  type="primary"
                  slot="reference"
                  v-if="isStudent && (item.state === 6 || item.state === 7) "
                >确认完成维修</el-button>
              </el-popconfirm>
              <el-popover
                placement="right"
                width="400"
                trigger="click"
              >
                <el-form
                  :inline="true"
                  :model="back"
                  ref="backForm"
                  :rules="backRules"
                  class="demo-form-inline"
                >
                  <el-form-item prop='cause'>
                    <el-input
                      clearable
                      v-model.trim="back.cause"
                      placeholder="请输入退回原因"
                      @keyup.enter.native="acceptRepairFn(item.id, true)"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      @click="acceptRepairFn(item.id, true)"
                    >确定</el-button>
                  </el-form-item>
                </el-form>
                <el-button
                  v-if="!isStudent && (item.state === 4 || item.state === 5)"
                  size="small"
                  type="danger"
                  slot="reference"
                >退回管理员处</el-button>
              </el-popover>
              <el-button
                v-if="!isStudent && item.state === 5"
                type="primary"
                size="small"
                @click="$router.push(
                    {
                      path: `/record/add/${item.id}`,
                    }
                  )"
              >填写维修记录</el-button>
              <el-button
                v-else-if="!isStudent && item.state === 4"
                size="small"
                type="primary"
                @click="acceptRepairFn(item.id, false)"
              >接单</el-button>
              <el-button
                v-else-if="!isStudent && (item.state === 6 || item.state === 7)"
                type="primary"
                size="small"
                @click="$router.push(
                    {
                      path: `/record/update/${item.m_id}`,
                    }
                  )"
              >修改维修记录</el-button>
            </el-col>
          </el-row>
        </div>
        <el-empty
          v-else
          :image-size="200"
        ></el-empty>

        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px; margin-top: 40px;"
          v-if="total > query.pagesize"
        >
          <!-- 分页区域 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="query.page"
            :page-size="query.size"
            layout="prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>

      </el-card>
    </div>
  </div>
</template>

<script>
import {
  affirmRepairAPI,
  getMyRepairListAPI,
  getRepairTypeListAPI,
  getUserInfoTypeAPI,
  queryRepairAPI,
  returnRepairAPI,
  screenAreaListAPI
} from '@/api'
import { transTree, tagState, repairState } from '@/utils'

export default {
  name: 'repairList',
  data () {
    return {
      timer: null,
      isAll: false,
      state: 0,
      query: {
        page: 1, // 页码
        pagesize: 10, // 每页条数
        type_id: '',
        state: ''
      },
      repairList: [],
      total: 0, // 数据总条数
      repairTypeList: [],
      screenRules: {
        type_id: [
          {
            length: '16',
            type: 'string',
            message: '报修类型格式有误',
            trigger: 'blur'
          }
        ],
        state: [
          {
            type: 'string',
            length: '1',
            message: '状态格式有误',
            trigger: 'blur'
          }
        ]
      },
      queryForm: {
        id: ''
      },
      queryRules: {
        id: [
          {
            min: 32,
            max: 32,
            type: 'string',
            message: '报修单id要求32个字符',
            trigger: 'change'
          },
          { required: true, message: '报修单id不能为空', trigger: 'blur' }
        ]
      },
      isStudent: false,
      back: { cause: '' },
      backRules: {
        cause: [
          {
            type: 'string',
            min: 1,
            max: 200,
            message: '退回原因要求1-200字符',
            trigger: 'blur'
          },
          { required: true, message: '退回原因不能为空', trigger: 'blur' }
        ]
      },
      repairState,
      tagState,
      areaOptions: {}
    }
  },
  async created () {
    await this.initFn()
    await this.getRepairTypeListFn() // 获取报修类型
    this.getRepairListFn() // 获取报修单列表
    this.getAreaFn()
  },
  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.size = newSize
      this.getRepairListFn() // 获取报修单列表
    },
    // 获取维修区域 -> 发送请求
    async getAreaFn () {
      try {
        const { success, code, data } = await screenAreaListAPI({
          page: 1
        })
        if (success && code === 10000) {
          data.forEach((item) => {
            this.$set(this.areaOptions, item.id, {
              value: item.id,
              label: item.name
            })
          })
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getRepairListFn() // 获取报修单列表
    },
    // 获取报修单列表 -> 发送请求
    async getRepairListFn () {
      clearTimeout(this.timer)
      this.timer = this.isStudent
        ? setInterval(this.getRepairListFn, 1000 * 60 * 10)
        : setInterval(this.getRepairListFn, 1000 * 60)
      try {
        const { success, code, data } = await getMyRepairListAPI({
          ...this.query,
          state: this.query.state
            ? parseInt(this.query.state)
            : this.state === 1
              ? this.isStudent ? 3 : 4
              : this.state === 2
                ? this.isStudent ? -1 : -4
                : this.state === 3 ? 6 : ''
        })
        if (success && code === 10000) {
          this.repairList = data.row
          this.total = data.total
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 获取报修类型列表 -> 发送请求
    async getRepairTypeListFn () {
      try {
        const { success, code, data } = await getRepairTypeListAPI()
        if (success && code === 10000) {
          this.repairTypeList = transTree(data, '')
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 筛选
    screenSubmitFn () {
      try {
        this.$refs.screenForm.validate(async (valid) => {
          if (valid) {
            this.getRepairListFn()
          }
        })
      } catch (err) {
        return console.dir(err)
      }
    },
    // 重置
    resetForm () {
      this.$refs.queryForm.resetFields()
    },
    // 接单/退回
    acceptRepairFn (id, isReturn) {
      try {
        this.$refs.backForm[0].validate(async (valid) => {
          if (!isReturn || valid) {
            const { success, code } = await returnRepairAPI({
              id,
              isReturn,
              cause: this.back.cause
            })
            if (success && code === 10000) {
              success && (await this.getRepairListFn()) // 获取报修单列表
            }
          }
        })
      } catch (err) {
        return console.dir(err)
      }
    },
    // 完成维修/未完成维修
    affirmRepairFn (id, isAffirm) {
      try {
        this.$refs.backForm[0].validate(async (valid) => {
          if (isAffirm || valid) {
            const { success, code } = await affirmRepairAPI({
              id,
              isAffirm,
              cause: this.back.cause
            })
            if (success && code === 10000) {
              success && (await this.getRepairListFn()) // 获取报修单列表
            }
          }
        })
      } catch (err) {
        return console.dir(err)
      }
    },
    // 查询报修单
    getQueryFn () {
      try {
        this.$refs.queryForm.validate(async (valid) => {
          if (valid) {
            const { success, code, data } = await queryRepairAPI(
              {
                id: this.queryForm.id,
                state: this.query.state
                  ? parseInt(this.query.state)
                  : this.state === 1
                    ? this.isStudent ? 3 : 4
                    : this.state === 2
                      ? this.isStudent ? -1 : 5
                      : this.state === 3 ? 6 : ''
              }
            )
            if (success && code === 10000) {
              this.repairList = [data]
            }
          }
        })
      } catch (err) {
        return console.dir(err)
      }
    },
    // 清空筛选数据 -> 重新获取列表
    screenResetFn () {
      this.query = this.$options.data().query
      this.$refs.screenForm?.resetFields()
      this.getRepairListFn()
    },
    // init
    async initFn () {
      const type = (await getUserInfoTypeAPI()).data.type
      if (type === 1) {
        this.isStudent = true
      }
      const path = this.$route.path
      switch (path) {
        case '/repair/wait':
          this.state = 1
          break
        case '/repair/underway':
          this.state = 2
          break
        case '/repair/complete':
          this.state = 3
          break
        case '/repair/all':
          this.state = 4
          break
      }
    }
  },
  // 销毁实例
  beforeDestroy () {
    clearTimeout(this.timer)
    this.timer = null
  }
}
</script>

<style lang="less" scoped>
.list {
  min-width: 740px;
  margin-top: 10px;
  border-bottom: 1px solid #dcdfe6;
}
.box-card .body {
  padding: 0 50px;
}
</style>
